package utils

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"runtime"
	"time"
)

func MongoClient(dsn string) (*mongo.Client, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	cpuNum := uint64(runtime.NumCPU())
	opt := options.Client().ApplyURI(dsn)
	opt.SetMinPoolSize(cpuNum)
	opt.SetMaxPoolSize(cpuNum * 4)
	return mongo.Connect(ctx, opt)
}

func MongoPing(client *mongo.Client) error {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()
	return client.Ping(ctx, readpref.Primary())
}

/*

func add() {
	test := client.Database("play_with_go").Collection("test")
	res, err := test.InsertOne(context.TODO(), bson.M{"name": "wang", "age": 13})
	utils.VarDump(res, err)
}

func addD() {
	test := client.Database("play_with_go").Collection("test")
	res, err := test.InsertOne(context.TODO(), bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}})
	utils.VarDump(res, err)
}

func find() {
	test := client.Database("play_with_go").Collection("test")
	cur, err := test.Find(context.Background(), bson.M{"age": bson.M{"$gte": 11}})
	if err != nil {
		utils.VarDump(err)
	}
	for cur.Next(context.Background()) {
		var res bson.M
		if err = cur.Decode(&res); err != nil {
			utils.VarDump(err)
		}
		utils.VarDump(res)
	}
}

*/
